// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-25

package list

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib/authorizer"
)

// Logic
// 订单列表.
type Logic struct {
	auth     *authorizer.Authentication
	request  *Request
	response []*Response
}

func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		conditions = map[string]any{
			"user_id": o.auth.UserId,
			"state":   o.request.State,
		}
		err     error
		ids     = make([]int64, 0)
		items   []*models.OrderUser
		res     = result.New()
		service = services.NewOrderUserService()
		total   int64
	)

	// 1. 订单列表.
	if items, total, err = service.Paging(ctx, conditions, o.request.Page, o.request.Size); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 遍历数据.
	for _, item := range items {
		ids = append(ids, item.OrderId)
		o.response = append(o.response, (&Response{}).With(item))
	}

	// 3. 订单数据.
	if len(ids) > 0 {
		if err = o.RunOrder(ctx, ids); err != nil {
			return res.WithError(err)
		}
	}

	return res.WithPaging(o.response, total, o.request.Page, o.request.Size)
}

// RunOrder
// 订单信息.
func (o *Logic) RunOrder(ctx context.Context, ids []int64) (err error) {
	var (
		aid    = make([]kind.ArcadeId, 0)
		mapper map[int64]*models.Order
	)

	// 1. 订单列表.
	if mapper, err = services.NewOrderService().MapByIdList(ctx, ids); err != nil {
		return
	}

	// 2. 遍历订单.
	for _, r := range o.response {
		if v, ok := mapper[r.OrderId]; ok {
			if v.ArcadeId.IsBound() {
				aid = append(aid, v.ArcadeId)
			}
			r.WithOrder(v)
		}
	}

	// 3. 绑定钓场.
	if len(aid) > 0 {
		err = o.RunOrderArcade(ctx, aid)
	}
	return
}

func (o *Logic) RunOrderArcade(ctx context.Context, ids []kind.ArcadeId) (err error) {
	var mapper map[kind.ArcadeId]*models.Arcades

	// 1. 钓场列表.
	if mapper, err = services.NewArcadesService().MapByIdList(ctx, ids); err != nil {
		return
	}

	// 2. 遍历订单.
	for _, r := range o.response {
		if r.Order != nil && r.Order.ArcadeId.IsBound() {
			if v, ok := mapper[r.Order.ArcadeId]; ok {
				r.Order.WithArcade(v)
			}
		}
	}
	return
}
